<script setup>
import { ref, onMounted } from 'vue'

const selectedCategory = ref('')
const categories = ref([])
const products = ref([])
const loading = ref(false)
const error = ref('')

// 购买弹窗相关
const showBuyModal = ref(false)
const selectedProduct = ref({})
const buyQuantity = ref(1)
const totalAmount = ref(0)

// 获取分类列表
const fetchCategories = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch('http://localhost:7070/getsortlist')
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 检查API响应格式
    if (result.code === 200 && result.data) {
      categories.value = result.data
    } else {
      throw new Error(result.msg || '获取数据失败')
    }
    
  } catch (err) {
    error.value = `获取分类数据失败: ${err.message}`
    console.error('获取分类失败:', err)
    
    // 设置默认分类作为备选
    categories.value = [
      { id: 1, name: '文具' },
      { id: 2, name: '小电器' },
      { id: 3, name: '食品' },
      { id: 4, name: '服装' }
    ]
  } finally {
    loading.value = false
  }
}

// 根据分类获取商品列表
const fetchProductsByCategory = async () => {
  loading.value = true
  error.value = ''
  
  try {
    let url = 'http://localhost:7070/All'
    if (selectedCategory.value) {
      url += `?sortId=${selectedCategory.value}`
    }
    
    const response = await fetch(url)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const result = await response.json()
    
    // 检查API响应格式
    if (result.code === 200 && result.data) {
      products.value = result.data
    } else {
      throw new Error(result.msg || '获取商品数据失败')
    }
    
  } catch (err) {
    error.value = `获取商品数据失败: ${err.message}`
    console.error('获取商品失败:', err)
    products.value = []
  } finally {
    loading.value = false
  }
}

// 打开购买弹窗
const openBuyModal = (product) => {
  selectedProduct.value = { ...product }
  buyQuantity.value = 1
  calculateTotal()
  showBuyModal.value = true
}

// 关闭购买弹窗
const closeBuyModal = () => {
  showBuyModal.value = false
  selectedProduct.value = {}
  buyQuantity.value = 1
  totalAmount.value = 0
}

// 计算总金额
const calculateTotal = () => {
  const quantity = parseInt(buyQuantity.value) || 0
  totalAmount.value = quantity * selectedProduct.value.price
}

// 确认购买
const confirmPurchase = async () => {
  if (!buyQuantity.value || buyQuantity.value <= 0) {
    alert('请输入正确的购买数量')
    return
  }
  
  if (buyQuantity.value > selectedProduct.value.remaining) {
    alert('购买数量不能超过剩余数量')
    return
  }

  try {
    // 更新商品库存
    const updatedProduct = {
      ...selectedProduct.value,
      remaining: selectedProduct.value.remaining - buyQuantity.value
    }

    // 这里可以调用后端API更新库存
    // const response = await fetch('http://localhost:7070/drop', {
    //   method: 'POST',
    //   headers: { 'Content-Type': 'application/json' },
    //   body: JSON.stringify(updatedProduct)
    // })

    // 本地更新商品列表
    const productIndex = products.value.findIndex(p => p.id === selectedProduct.value.id)
    if (productIndex !== -1) {
      products.value[productIndex].remaining = updatedProduct.remaining
    }

    alert(`购买成功！\n商品：${selectedProduct.value.name}\n数量：${buyQuantity.value}\n总金额：${totalAmount.value.toFixed(2)}元`)
    closeBuyModal()
    
  } catch (err) {
    error.value = `购买失败: ${err.message}`
    console.error('购买失败:', err)
  }
}

// 组件挂载时获取数据
onMounted(async () => {
  await fetchCategories()
  await fetchProductsByCategory()
})
</script>

<template>
  <div class="shop-container">
    <div class="header">
      <h1 class="title">商店销售系统</h1>
    </div>
    
    <div class="filter-section">
      <label for="category-select">请选择商品分类：</label>
      <select id="category-select" v-model="selectedCategory" @change="fetchProductsByCategory" class="category-select">
        <option value="">全部</option>
        <option v-for="category in categories" :key="category.id" :value="category.id">
          {{ category.name }}
        </option>
      </select>
    </div>

    <div class="table-container">
      <table class="product-table">
        <thead>
          <tr>
            <th>序号</th>
            <th>商品名称</th>
            <th>商品分类</th>
            <th>产地</th>
            <th>生产日期</th>
            <th>单价(元)</th>
            <th>剩余数量</th>
            <th>购买</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(product, index) in products" :key="product.id">
            <td>{{ index + 1 }}</td>
            <td>{{ product.name }}</td>
            <td>{{ product.sortName }}</td>
            <td>{{ product.address }}</td>
            <td>{{ product.createDate }}</td>
            <td>{{ product.price }}</td>
            <td>{{ product.remaining }}</td>
            <td>
              <button 
                class="buy-btn"
                @click="openBuyModal(product)"
                :disabled="product.remaining === 0"
              >
                {{ product.remaining > 0 ? '购买' : '无货' }}
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 购买商品弹窗 -->
    <div v-if="showBuyModal" class="modal-overlay" @click="closeBuyModal">
      <div class="buy-modal" @click.stop>
        <h2 class="modal-title">购买商品</h2>
        
        <div class="product-info">
          <div class="info-row">
            <label>商品编号</label>
            <span>{{ selectedProduct.id }}</span>
          </div>
          <div class="info-row">
            <label>商品名称</label>
            <span>{{ selectedProduct.name }}</span>
          </div>
          <div class="info-row">
            <label>商品分类</label>
            <span>{{ selectedProduct.sortName }}</span>
          </div>
          <div class="info-row">
            <label>单价(元)</label>
            <span>{{ selectedProduct.price }}</span>
          </div>
          <div class="info-row">
            <label>剩余数量</label>
            <span>{{ selectedProduct.remaining }}</span>
          </div>
          <div class="info-row">
            <label>购买数量</label>
            <div class="quantity-input">
              <input 
                type="number" 
                v-model="buyQuantity" 
                :max="selectedProduct.remaining"
                min="1"
                @input="calculateTotal"
              >
              <span class="quantity-note">数量不能为空</span>
            </div>
          </div>
          <div class="info-row total-row">
            <label>总金额(元)</label>
            <span class="total-amount">{{ totalAmount.toFixed(2) }}</span>
          </div>
        </div>

        <div class="modal-buttons">
          <button class="btn-primary" @click="confirmPurchase" :disabled="!buyQuantity || buyQuantity <= 0">
            购买
          </button>
          <button class="btn-secondary" @click="closeBuyModal">
            返回
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态提示 -->
    <div v-if="loading" class="loading">
      正在加载数据...
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="error">
      {{ error }}
    </div>
  </div>
</template>

<style scoped>
.shop-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
}

.header {
  text-align: center;
  margin-bottom: 30px;
}

.title {
  font-size: 2.5rem;
  color: #2c3e50;
  margin: 0;
  font-weight: bold;
  text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-section label {
  font-weight: 600;
  color: #495057;
}

.category-select {
  padding: 8px 12px;
  border: 2px solid #dee2e6;
  border-radius: 5px;
  background: white;
  font-size: 14px;
  cursor: pointer;
  transition: border-color 0.3s ease;
}

.category-select:focus {
  outline: none;
  border-color: #007bff;
}

.table-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.product-table {
  width: 100%;
  border-collapse: collapse;
}

.product-table th {
  background: #343a40;
  color: white;
  padding: 15px 10px;
  text-align: center;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
}

.product-table td {
  padding: 12px 10px;
  text-align: center;
  border-bottom: 1px solid #dee2e6;
}

.product-table tbody tr:nth-child(even) {
  background: #f8f9fa;
}

.product-table tbody tr:hover {
  background: #e3f2fd;
  transition: background-color 0.3s ease;
}

.buy-btn {
  background: #007bff;
  color: white;
  border: none;
  padding: 6px 16px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.buy-btn:hover:not(:disabled) {
  background: #0056b3;
  transform: translateY(-1px);
}

.buy-btn:disabled {
  background: #6c757d;
  cursor: not-allowed;
  opacity: 0.6;
}

.buy-btn:active {
  transform: translateY(0);
}

/* 购买弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.buy-modal {
  background: white;
  border-radius: 10px;
  padding: 25px;
  width: 90%;
  max-width: 500px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-title {
  text-align: center;
  margin: 0 0 25px 0;
  font-size: 1.5rem;
  color: #2c3e50;
  font-weight: 600;
}

.product-info {
  margin-bottom: 25px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-row:last-child {
  border-bottom: none;
}

.info-row label {
  font-weight: 500;
  color: #495057;
  min-width: 100px;
}

.info-row span {
  color: #212529;
}

.quantity-input {
  display: flex;
  align-items: center;
  gap: 10px;
}

.quantity-input input {
  width: 80px;
  padding: 5px 8px;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  text-align: center;
}

.quantity-note {
  font-size: 12px;
  color: #6c757d;
}

.total-row {
  border-top: 2px solid #dee2e6;
  margin-top: 10px;
  padding-top: 15px;
  font-weight: 600;
}

.total-amount {
  color: #dc3545;
  font-size: 1.1rem;
  font-weight: 600;
}

.modal-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.btn-primary {
  background: #007bff;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-primary:hover:not(:disabled) {
  background: #0056b3;
}

.btn-primary:disabled {
  background: #6c757d;
  cursor: not-allowed;
}

.btn-secondary {
  background: #6c757d;
  color: white;
  border: none;
  padding: 10px 25px;
  border-radius: 5px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-secondary:hover {
  background: #545b62;
}

.loading {
  text-align: center;
  padding: 20px;
  color: #007bff;
  font-weight: 500;
}

.error {
  text-align: center;
  padding: 15px;
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 5px;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .shop-container {
    padding: 10px;
  }
  
  .title {
    font-size: 2rem;
  }
  
  .table-container {
    overflow-x: auto;
  }
  
  .product-table {
    min-width: 600px;
  }
  
  .filter-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .buy-modal {
    width: 95%;
    margin: 20px;
  }

  .modal-buttons {
    flex-direction: column;
  }

  .info-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}
</style>
